<template>
  <div>
    <!-- 面包屑导航 -->
    <breadcrumbs :data1="data1" :data2="data2"></breadcrumbs>
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <el-steps :space="200" :active="+activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addrules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(单位:元)" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(单位:g)" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="CateList"
                :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name' }"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  size="mini"
                  v-for="(items,i) in item.attr_vals"
                  :key="i"
                  :label="items"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="uploadHeaders"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <el-dialog
              title="图片预览"
              :visible.sync="previewdialogVisible"
              width="30%"
              :before-close="handleClose"
            >
              <img :src="previewURL" class="previewImg">
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" size="medium" class="addBtn" @click="addCate">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
           
<script>
import breadcrumbs from '@/common/breadcrumbs'
import _ from 'lodash'
export default {
  data () {
    return {
      data1: '商品管理',
      data2: '添加商品',
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        pics: [],
        goods_introduce: '',
        attrs:[]
      },
      CateList: [],
      manyTableData: [],
      onlyTableData: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      uploadHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewURL: '',
      previewdialogVisible: false,
      addrules: {
        goods_name: [
          { required: true, message: '商品名称不能为空！', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格不能为空！', trigger: 'blur' },
          { min: 0, max: 6, message: '范围：0 ~ 999999', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品重量不能为空！', trigger: 'blur' },
          { min: 0, max: 6, message: '范围：0 ~ 999999', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品数量不能为空！', trigger: 'blur' },
          { min: 0, max: 6, message: '范围：0 ~ 999999', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择分类！', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.CateList = res.data

    },
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName == 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类 ')
        return false
      }
    },
    async tabClicked () {
      // activeIndex == 1访问的是商品参数面板
      if (this.activeIndex == 1) {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length == 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex == 2) {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        console.log(res.data);
        this.onlyTableData = res.data
      }
    },
    handlePreview (file) {
      this.previewdialogVisible = true
      this.previewURL = file.response.data.url
    },
    handleRemove (file) {
      const path = file.response.data.tmp_path
      const removeIndex = this.addForm.pics.findIndex(x => {
        return x.pic == path
      })
      this.addForm.pics.splice(removeIndex, 1)
      console.log(this.addForm.pics)
    },
    handleSuccess (res) {
      const picInfo = { 'pic': res.data.tmp_path }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics);
    },
    handleClose () {
      this.previewdialogVisible = false
      this.previewURL = ''
    },
    addCate () {
      this.$refs.addFormRef.validate(async val => {
        if (val) {
          const newForm = _.cloneDeep(this.addForm)
          newForm.goods_cat = newForm.goods_cat.join(',')
          this.manyTableData.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
            this.addForm.attrs.push(newInfo)
          })
          this.onlyTableData.forEach(item => {
            const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
            this.addForm.attrs.push(newInfo)
          })
          newForm.attrs = this.addForm.attrs
          const {data:res} = await this.$http.post('goods',newForm)
          if(res.meta.status == 201){
            this.$message.success('商品添加成功~')
            this.$router.push('/goods')
          }else{
            this.$message.error(res.meta.msg)
          }
        } else {
          this.$message.error('请检查基本信息是否合法！')
        }
      })
    }
  },
  created () {
    this.getCateList()
  },
  components: {
    breadcrumbs
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  }
}
</script>
<style scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.addBtn {
  margin-top: 15px;
}
</style>